package com.kanshu.ksgb.fastread.doudou.common.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;

import com.kanshu.ksgb.fastread.doudou.R;

/**
 * Created by wcy on 18/6/6.
 */

public class LinaerGradientTextView extends AppCompatTextView {
    private LinearGradient mLinearGradient;
    private Paint mPaint;
    private int mViewWidth = 0;
    private Rect mTextBound = new Rect();
    private int mStartColor, mEndColor;
    public LinaerGradientTextView(Context context) {
        super(context);
    }

    public LinaerGradientTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initAttrs(attrs);
    }

    public LinaerGradientTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttrs(attrs);
    }

    private void initAttrs(AttributeSet attrs) {
        if (attrs != null) {
            TypedArray typedArray =
                    getContext().obtainStyledAttributes(attrs, R.styleable.LinaerGradientTextView);
            mStartColor = typedArray.getColor(R.styleable.LinaerGradientTextView_startColor, 0xFF429321);
            mEndColor = typedArray.getColor(R.styleable.LinaerGradientTextView_endColor, 0xFFB4EC51);
            typedArray.recycle();
        }
    }

    public void setLinearGradientColor(int ... gradientColor) {
        mStartColor = gradientColor[0];
        mEndColor = gradientColor[1];
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mViewWidth = getMeasuredWidth();
        mPaint = getPaint();
        String mTipText = getText().toString();
        mPaint.getTextBounds(mTipText, 0, mTipText.length(), mTextBound);
        mLinearGradient = new LinearGradient(0, 0, mViewWidth, 0,
                new int[] {  mStartColor, mEndColor },
                null, Shader.TileMode.REPEAT);
        mPaint.setShader(mLinearGradient);
        canvas.drawText(mTipText, getMeasuredWidth() / 2 - mTextBound.width() / 2, getMeasuredHeight() / 2 +   mTextBound.height()/2, mPaint);
    }


}
